local HOME_URL = 'https://gamecloud-test.qiyi.domain/'
local SSO_VALIDATE_URL = 'https://sso.qiyi.com/cas/serviceValidate'
local SSO_LOGIN_URL = 'https://sso.qiyi.com/cas/login'
local COOKIE_MAX_AGE = 3600 * 24

local JSON = require 'cjson'


-- 安全URL
local function url_safe(host, params)
  local result = {}

  for k, v in pairs(params) do
    table.insert(result, k .. '=' .. ngx.escape_uri(v))
  end

  return host .. '?' .. table.concat(result, '&')
end


-- 生成授权码
local function gen_token(user_name)
  local resp = ngx.location.capture(
    '/authorization',
    { args={ user_name=user_name } }
  )
  ngx.log(ngx.ERR, resp.status, resp.body)
  if resp.status ~= 200 then
    return 1, resp.status
  end

  local data = JSON.decode(resp.body)
  if data['status'] == 0 then
    return 0, data['data']['token']
  else
    return 1, data['data']
  end
end


local ticket = ngx.var.arg_ticket
if ticket ~= nil then
  local http = require "resty.http"
  local httpc = http.new()
  local redirect_url = url_safe(SSO_VALIDATE_URL, { service=HOME_URL }) .. '&ticket=' .. ticket

  local res, err = httpc:request_uri(redirect_url, { method="GET", ssl_verify=false })
  if not res then
    ngx.say("failed to request: ", err)
    return
  end

  local result = res.body
  if result:find("authenticationSuccess", 1) ~= nil then
    local q, m = result:find("<cas:user>", 1)
    local n = result:find("</cas:user>", 1)

    if m ~= nil and n ~= nil then
      local user_name = result:sub(m+1,n-1)
      local err, token = gen_token(user_name)

      if err ~= 0 then
        local resp = { status=403, msg='fail', data=token }
        return ngx.say(JSON.encode(resp))

      else
        local res_data = "token=" .. token .. "; path=/; max-age=" .. COOKIE_MAX_AGE .. "; secure"
        ngx.header["Set-Cookie"] = {res_data}
        return ngx.redirect(HOME_URL)
      end

    else
      return ngx.say("sad :( parse sso return error" .. result)
    end
  else
    ngx.log(ngx.ERR, "authentication failed!")
    return ngx.exit(403)
  end
end


if ngx.var.cookie_token == nil then
  ngx.redirect(url_safe(SSO_LOGIN_URL, { service=HOME_URL }))
end
